﻿using System.Reactive;
using System.Threading.Tasks;
using MilkTeaMachine.OfflineClient.Utils;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;

namespace MilkTeaMachine.OfflineClient.ViewModels;

public class FactorySettingsLoginViewModel : ViewModelBase, IRoutableViewModel
{
    public FactorySettingsLoginViewModel(IScreen hostScreen)
    {
        HostScreen = hostScreen;
        LoginCmd = ReactiveCommand.CreateFromTask(LoginAsync,
            this.WhenAnyValue(
                vm => vm.Username,
                vm => vm.Password,
                (u, p) => !string.IsNullOrWhiteSpace(u) && !string.IsNullOrWhiteSpace(p)));
        GoWeightingCalibrationCmd = ReactiveCommand.CreateFromObservable(
            () => HostScreen.Router.Navigate.Execute(new WeightingCalibrationViewModel(HostScreen, 0x01)));
        PrePageCmd = ReactiveCommand.CreateFromObservable(
            () => HostScreen.Router.NavigateBack.Execute());
        SaveAndQuitCmd = ReactiveCommand.CreateFromTask(SaveAndQuitAsync);
    }

    public FactorySettingsLoginViewModel() : this(default!)
    {
    }

    private Task SaveAndQuitAsync()
    {
        HostScreen.Router.NavigateAndReset.Execute(new MainPageViewModel(HostScreen));
        return Task.CompletedTask;
    }

    private Task LoginAsync()
    {
        if (Username?.Equals("admin") is true && Password?.Equals("1q2w3E*") is true)
        {
            HostScreen.Router.Navigate.Execute(new FactorySettingsViewModel(HostScreen));
        }
        else
        {
            _ = MessageBoxUtil.GetBox("用户名或密码错误").ShowWindowAsync();
        }

        return Task.CompletedTask;
    }

    public string? UrlPathSegment { get; } = nameof(FactorySettingsLoginViewModel);
    public IScreen HostScreen { get; }
    public ReactiveCommand<Unit, IRoutableViewModel> PrePageCmd { get; }
    public ReactiveCommand<Unit, IRoutableViewModel> NextPageCmd { get; }
    public ReactiveCommand<Unit, Unit> SaveAndQuitCmd { get; }
    [Reactive] public string? Username { get; set; }
    [Reactive] public string? Password { get; set; }
    public ReactiveCommand<Unit, Unit> LoginCmd { get; set; }
    public ReactiveCommand<Unit, IRoutableViewModel> GoWeightingCalibrationCmd { get; }
}